var express = require('express');
var router = express.Router();
// var mysql = require('../dao/mysql')
var jwt = require('../utils/jwt')
var mysql = require('mysql')
var fs = require('fs')
var path = require('path')
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'cui1020',
  database: 'flask'
})

var multer = require('multer')
var upload = multer({ dest: 'uploads/' })

var jwt = require('../utils/jwt');
const { Template } = require('ejs');
router.get('/id/:id', function(req, res, next) {
	let user = connection.query('SELECT * from user', function (err, rows, fields) {
		console.log(err)
		if (err) throw err
		// return rows
		console.log('The solution is: ', rows[0].name)
		let data = {
			code:1,
			data:req.query,
			params:req.params,
			ip:req.ip,
			user:rows
		}
		res.json(data);
	})
});
router.post('/add', function(req, res, next) {
	var  addSql = 'INSERT INTO user(name,password,age,userImage) VALUES(?,?,?,?)';
	var  addSqlParams = [req.body.name, req.body.password,req.body.age,req.body.imageUrl];
	connection.query(addSql,addSqlParams, function (err, result, fields) {
		if (err) throw err
		if (result.affectedRows > 0) {
			let data = {
				code:1,
				result:'添加成功'
			}
			res.json(data);
		}else{
			res.json({'code':0,'result':'插入失败'});
		}
	})
})
router.get('/list', function(req, res, next) {
	// console.log(req.body.name)
	// console.log(req.body.password)
	// console.log(req.body.age)
	var  addSql = 'SELECT * FROM user LIMIT 0, 100';
	connection.query(addSql, function (err, result, fields) {
		if (err) throw err
		console.log(result)
		if (result.length > 0) {
			let data = {
				code:1,
				result:result
			}
			res.json(data);
		}else{
			res.json({'code':0,'result':'查询失败'});
		}
	})
})
router.post('/del', function(req, res, next) {
	// console.log(req.body.name)
	// console.log(req.body.password)
	// console.log(req.body.age)
	var delSql = 'DELETE FROM user where id='+req.body.id
	connection.query(delSql, function (err, result, fields) {
		if (err) throw err
		if (result.affectedRows > 0) {
			let data = {
				code:1,
				result:'删除成功'
			}
			res.json(data);
		}else{
			res.json({'code':0,'result':'删除失败'});
		}
	})
})
router.post('/update', function(req, res, next) {
	var modSql = 'UPDATE user SET name = ?,password = ?,age = ?,userImage = ? WHERE Id = ?';
	var modSqlParams = [req.body.name, req.body.password,req.body.age,req.body.userImage,req.body.id];
	connection.query(modSql,modSqlParams, function (err, result, fields) {
		if (err) throw err
		if (result.affectedRows > 0) {
			console.log(result)
			let data = {
				code:1,
				result:'更新成功'
			}
			res.json(data);
		}else{
			res.json({'code':0,'result':'更新失败'});
		}
	})
})


router.post('/login', function (req, res) {
    let username = req.body.name;   //用户名
    let password = req.body.password;   //用户名
	console.log(username)
	console.log(password)
	let token = jwt.generateToken(username);
    connection.query(`SELECT * FROM user WHERE name='${username}'`, function (err, data) {
		if (err) {
			res.send(err).end();
		} else {
			if (data.length > 0) {
				console.log(data)
			if (data[0].password === password) {
				res.send({
					code: 1, 
					data: data[0],
					msg:'登录成功',
					token:token
				}).end();
			} else {
				res.send({ code: 500, msg: "用户名或密码错误" }).end();
			}
			} else {
			res.send({ code: 500, msg: "用户名或密码错误" }).end();
			}
		}
    })
})

router.post('/uploadhead', upload.single('file'),function(req, res, next) {
	let file = req.file;
	console.log(file)
	if (!file) {
		res.send({
			code:0,
			msg:'没有文件！'
		})
	}else{
		let basepath = __dirname = 'uploads/';
		let tmp_path = req.file.path;
		let extname = path.extname(file.originalname);
		let target_path = `${basepath}${Date.now()}${extname}`;
		console.log(target_path)
		// console.log(target_path)
		fs.rename(tmp_path,target_path,function(err){
			if (err) {
				res.send({code:0})
			}else{
				res.send({
					code:1,
					url:target_path
				})
			}
		})
		// let readStream = fs.createReadStream(tmp_path)
		// let writeStream = fs.createWriteStream(target_path)
		// readStream.pipe(writeStream)
		// readStream.on('end',function(){
		// 	fs.unlinkSync(tmp_path)
		// 	fs.unlinkSync(target_path)
		// })
	// let data = {
	// 	code:1,
	// 	result:'上传成功',
	// 	url:target_path
	// }
	// res.json(data);
	}
	// var modSql = 'UPDATE user SET name = ?,password = ?,age = ? WHERE Id = ?';
	// var modSqlParams = [req.body.name, req.body.password,req.body.age,req.body.id];
	// connection.query(modSql,modSqlParams, function (err, result, fields) {
	// 	if (err) throw err
	// 	if (result.affectedRows > 0) {
	// 		console.log(result)
	// 		let data = {
	// 			code:1,
	// 			result:'更新成功'
	// 		}
	// 		res.json(data);
	// 	}else{
	// 		res.json({'code':0,'result':'更新失败'});
	// 	}
	// })
})






















module.exports = router;
